package edu.zju.gis.dbfg.server.controller;

import edu.zju.gis.dbfg.common.Result;
import edu.zju.gis.dbfg.common.base.BaseController;
import edu.zju.gis.dbfg.common.constant.CodeConstants;
import edu.zju.gis.dbfg.server.config.CommonSetting;
import edu.zju.gis.dbfg.server.constant.UserRole;
import edu.zju.gis.dbfg.server.model.Department;
import edu.zju.gis.dbfg.server.model.Role;
import edu.zju.gis.dbfg.server.model.User;
import edu.zju.gis.dbfg.server.model.search.UserSearch;
import edu.zju.gis.dbfg.server.model.userRegister;
import edu.zju.gis.dbfg.server.service.DepartmentService;
import edu.zju.gis.dbfg.server.service.RoleService;
import edu.zju.gis.dbfg.server.service.UserService;
import edu.zju.gis.dbfg.server.service.impl.RoleServiceImpl;
import edu.zju.gis.dbfg.server.util.MD5Tool;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author Hu
 * @date 2019/8/26
 **/
@CrossOrigin
@Controller
@RequestMapping("/user")
public class UserController extends BaseController<User, UserService, String, UserSearch> {
    @Autowired
    private RoleService roleService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private CommonSetting setting;
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public Result create(@RequestBody userRegister user) throws Exception {

        if (this.service.selectByName(user.getName())!=null) {
            return new Result().setCode(CodeConstants.USER_EXISTED);
        } else {
            String password = user.getPassword();
//            String key = "qwrwrww十多个";// 自定义密钥,个数不能太短，太短报错，过长，它默认只取前N位（N的具体值，大家另行查找资料）
//            MD5Tool mt = new MD5Tool(key, "utf-8");
//            //加密后的密码
//            String password2 = mt.getMD5Value(value);
            User user1 = new User();
            if (user.getDepartment() == "public") {
                user1.setId(UUID.randomUUID().toString());
                user1.setName(user.getName());
                user1.setPassword(password);
                user1.setRole("visitor");
            } else {
                Role usrRole = roleService.select(user.getDepartment(), Integer.parseInt(user.getLevel()));
                user1.setId(UUID.randomUUID().toString());
                user1.setName(user.getName());
                user1.setPassword(password);
                user1.setRole(usrRole.getId());
            }
//        user.setRole(UserRole.User);
            //用户注册后在用户空间下新建一个文件夹
            File dir = new File(setting.getSelfDataNameSpace()+user1.getId());
            if (!dir.exists()) {// 判断目录是否存在
                dir.mkdir();
            }
            return new Result(this.service.save(user1)).setCode(200);
        }
    }

    /**
     * 用户登录
     *
     * @param input
     * @param session
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result login(@RequestBody Map<String, Object> input, HttpSession session) throws Exception {
        String name = String.valueOf(input.get("name"));
        String pass = String.valueOf(input.get("password"));
//        String key = "qwrwrww十多个";// 自定义密钥,个数不能太短，太短报错，过长，它默认只取前N位（N的具体值，大家另行查找资料）
//        MD5Tool mt = new MD5Tool(key, "utf-8");
//        String pass2 = mt.getMD5Value(pass);
        User user = this.service.select(name, pass);
        if (user == null) {
            return Result.error("unvalid user name or password").setCode(CodeConstants.USERNAME_OR_PASSWORD_ERROR);
        } else {
            session.setAttribute("userId", user.getId());
            session.setAttribute("userName", user.getName());
            session.setAttribute("role", user.getRole());
            if(user.getRole().contains("Manager")){
                return new Result<User>().setBody(user).setCode(201);
            }else{
                return new Result<User>().setBody(user).setCode(200);
            }
        }
    }

    /**
     * 用户登出/注销
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public Result logout(HttpSession session) {
        try {
            session.removeAttribute("userId");
            session.removeAttribute("userName");
            session.removeAttribute("role");
            return Result.success().setMessage("logout success");
        } catch (RuntimeException e) {
            return Result.error("logout error").setCode(CodeConstants.SERVICE_ERROR);
        }
    }

    /**
     * 用户登陆状态
     *
     * @param session
     * @return userId
     */
    @RequestMapping(value = "/status", method = RequestMethod.GET)
    @ResponseBody
    public Result getloginstatus(HttpSession session) {
        Object userId = session.getAttribute("userId");
        if (userId != null) {
            User user = service.select(String.valueOf(userId));
            return Result.success().setBody(user);
        }
        return Result.error("has not login").setCode(CodeConstants.USER_NOT_EXIST);
    }

    /**
     * 测试，从session中读取id数据
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    @ResponseBody
    public Result test(HttpSession session) {
        Object userId = session.getAttribute("userId");
        if (userId != null) {
            User user = service.select(String.valueOf(userId));
            return Result.success().setBody(user);
        }
        return Result.error("has not log in").setCode(CodeConstants.USER_NOT_EXIST);
    }

    @RequestMapping(value = "/init", method = RequestMethod.POST)
    @ResponseBody
    public Result create() throws Exception {
        List<Department> departmentList = departmentService.selectAll();
        List<JSONObject> departments = new ArrayList<>();
        for (int i = 0; i < departmentList.size(); i++) {
            List<Role> roles = roleService.selectByDepartment(departmentList.get(i).getId());
            List<JSONObject> children = new ArrayList<>();
            for (int j = 0; j < roles.size(); j++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", roles.get(j).getUsrlevel());
                jsonObject.put("label", roles.get(j).getName());
                children.add(jsonObject);
            }
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("value", departmentList.get(i).getId());
            jsonObject2.put("label", departmentList.get(i).getName());
            jsonObject2.put("children", children);
            departments.add(jsonObject2);
        }
//        JSONObject outPutObj = new org.json.simple.JSONObject();
        return Result.success().setCode(200).setBody(departments);
    }
}
